const router = require("koa-router")({
  prefix: "/auth"
});
const responseCode = require("../../config/httpCode");
const userModel = require("../../db/models")["user"];
const jwt = require("jsonwebtoken");
const config = require("../../config/index");

router.post("/login", async ctx => {
  const { username, password } = ctx.request.body;
  const user = await userModel.findOne({
    where: {
      username,
      password
    }
  });
  if (user) {
    const token = jwt.sign(
      {
        username: user.username,
        id: user.id
      },
      config.jwt_token
    );
    ctx.body = {
      code: 200,
      data: {
        user,
        token
      }
    };
  } else {
    throw responseCode.NOT_VALIDATE;
  }
});
router.post("/register", async ctx => {
  const { username, password } = ctx.request.body;
  if (username.length <= 3) {
    throw responseCode.ACCOUNT_INVALIDE;
  }
  if (password.length < 6) {
    throw responseCode.PASSWORD_INVALIDE;
  }
  const user = await userModel.findOne({
    where: {
      username
    }
  });
  if (user) {
    throw responseCode.USER_EXIST;
  } else {
    await userModel.create({
      username,
      password
    });
    ctx.body = {
      code: 200
    };
  }
});
router.post("/admin", async ctx => {
  const { username, password } = ctx.request.body;
  if (username === "admin" && password === "admin") {
    const token = jwt.sign(
      {
        username
      },
      config.jwt_token
    );
    ctx.body = {
      code: 200,
      data: {
        token: token,
        username
      }
    };
  }
});
module.exports = router;
